package com.thinta.wind.ui.home.repository

import androidx.paging.DataSource
import androidx.paging.PageKeyedDataSource
import com.thinta.wind.base.safetyLaunch
import com.thinta.wind.entity.HomeDailyItemListBean
import com.thinta.wind.network.RetrofitManager
import kotlinx.coroutines.*

/*********************************************************
 * 版权信息：2021/6/8 10:43北京振中电子技术有限公司版权所有<p>
 * 创建作者：Wind<p>
 * 创建日期：2021/6/8 10:43<p>
 * *******************************************************<p>
 * 更新历史：    作者      日期      更新摘要<p>
 * <p>
 * *******************************************************<p>
 * 类功能说明：<p>
 */

class DailyRepository{

    suspend fun getHomeDailyList(): List<HomeDailyItemListBean>? = withContext(Dispatchers.IO){
        val result = RetrofitManager.apiService.getHomeDailyList(System.currentTimeMillis().toString()).itemList
        val filterData = result.filter {
            it.type == "followCard"
        }
        filterData
    }

}

class DailyDataSource(private val repository: DailyRepository) : PageKeyedDataSource<Int, HomeDailyItemListBean>(), CoroutineScope by MainScope(){

    override fun loadInitial(
        params: LoadInitialParams<Int>,
        callback: LoadInitialCallback<Int, HomeDailyItemListBean>
    ) {
        safetyLaunch {
            val result = repository.getHomeDailyList()
            result?.let {
                callback.onResult(it,1,2)
            }
        }
    }

    override fun loadBefore(
        params: LoadParams<Int>,
        callback: LoadCallback<Int, HomeDailyItemListBean>
    ) {

    }

    override fun loadAfter(
        params: LoadParams<Int>,
        callback: LoadCallback<Int, HomeDailyItemListBean>
    ) {

    }

    override fun invalidate() {
        super.invalidate()
        cancel()
    }

}

class DailyDataSourceFactory(private val repository: DailyRepository) :
    DataSource.Factory<Int, HomeDailyItemListBean>() {
    override fun create(): DataSource<Int, HomeDailyItemListBean>
            = DailyDataSource(repository)
}